package net.util.jport.ports.jdbc;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

import static java.lang.Math.min;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Connection Pool.
 */
public class ConnectionPool {

    private final int size;
    private final String uri;
    private final PoolingDataSource dataSource;

    public ConnectionPool(int sizeArg, String uriArg) {
        this.size = sizeArg <= 0 ? 0 : sizeArg;
        this.uri = uriArg;

        GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
        poolConfig.maxActive = size == 0 ? GenericObjectPool.DEFAULT_MAX_ACTIVE : size;
        poolConfig.maxIdle = min(poolConfig.maxActive, 5);

        ObjectPool connectionPool = new GenericObjectPool(null, poolConfig);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri,null);
        PoolableConnectionFactory poolableConnectionFactory =
                new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
        this.dataSource = new PoolingDataSource(connectionPool);
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public int getSize() {
        return size;
    }

    public String getUri() {
        return uri;
    }

    public PoolingDataSource getDataSource() {
        return dataSource;
    }

}
